package com.lin.pan.web.validator;

import com.lin.pan.core.constants.RPanConstants;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * 统一参数校验器配置
 */
@SpringBootConfiguration
@Slf4j
public class WebValidatorConfig {

    /**
     * 快速失败key
     */
    private static final String FAIL_FAST_KEY = "lin.validator.fail_fast";

    /**
     * 参数后置处理器
     * 每次方法执行时，通过参数校验对象去拦截，通过validation注解去查看参数是否符合我们的预期，不符合就拦截。
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        postProcessor.setValidator(rPanValidator());
        log.info("the hibernate validator is loaded successfully!");
        return postProcessor;
    }

    @Bean
    public Validator rPanValidator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .addProperty(FAIL_FAST_KEY, RPanConstants.TRUE_STR)
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }

}